const http = require("./http")
const cache = require("./cache")

/**
 * 获取记录列表
 */
async function getRecords(){
    const {data:{records=[]}} = await http.post("/Record.List")
    const list = records.map(record=>({
        ip:record.value,
        id:typeof record.id==="string"?parseInt(record.id,10):record.id,
        sub_domain:record.name
    }))

    cache.set("records",list,0)

    return list
}



/**
 * 添加记录
 * @param {*} ip 
 * @param {*} sub_domain 
 */
async function addRecord(ip,sub_domain){
    return http.post("/Record.Create",{
        value:ip,
        sub_domain
    })
}

/**
 * 更新记录
 * @param {*} id 
 * @param {*} ip 
 * @param {*} sub_domain 
 */
async function modifyRecord(id,ip,sub_domain){
    return http.post("/Record.Modify",{
        record_id:id,
        value:ip,
        sub_domain
    })
}

async function setRecord(sub_domains,ip){
    if(!sub_domains.length) return Promise.reject(`更新DNS失败：${Array.isArray(sub_domains)?"sub_domains为空":"sub_domains不是数组"}`)
    let records = await getRecords()


    let newAdd = []

    if(records.length){
        // 过滤不存在的记录
        records = records.filter(record=>{
            const filter = sub_domains.includes(record.sub_domain)
            return filter
        })
        sub_domains.filter(sub=>{
            return records.every(record=>record.sub_domain!==sub)
        }).forEach(sub=>{
            newAdd.push([
                ip,
                sub
            ])
        })
    }else{
        newAdd = sub_domains.map(sub_domain=>([
            ip,
            sub_domain
        ]))
    }

    console.log(records,newAdd)

    // 更新已存在记录
    const updates = records.map(async record=>{
        if(record.ip!==ip){
            // IP不一致才更新
            // console.log("modify:",ip)
            console.log('===========================\n',
            `正在更新${record.sub_domain}，原IP：${record.ip}，目标ip:${ip}`,
            "===========================\n")
            modifyRecord(
                record.id,
                ip,
                record.sub_domain
            ).then(()=>{
                console.log('===========================\n',`${record.sub_domain}更新成功`,'===========================\n')
            })
            .catch(error=>{
                console.log('===========================\n',
                `${record.name}更新失败,`,{
                    record_id:record.id,
                    ip
                },'===========================\n')
                return Promise.reject(error)
            })
        }else{
            console.warn(`sub_domain:${record.sub_domain},ip:${record.ip},IP相同，不需要更新，`)
        }
    })

    // 添加不存在的记录
    newAdd.forEach(async add=>{
        await addRecord(...add).catch(error=>{
            console.log('===========================\n',
            "添加记录失败：",{
                ip:add[0],
                sub_domain:add[1]
            },'===========================\n')
            return Promise.reject(error)
        }).then(()=>{
            console.log(
                '===========================\n',
                `${add.join(',')}添加记录成功`
            )
        })
    })

    getRecords()

    return Promise.resolve()
}



module.exports = {
    getRecords,
    setRecord,
    addRecord,
    modifyRecord,
}